package com.txsj.scan.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.EpcInfoDao;
import com.nativec.tools.ModuleManager;
import com.txsj.scan.Constants;
import com.txsj.scan.R;
import com.txsj.scan.activity.allocationapply.AllocationEpcActivity;
import com.txsj.scan.adapter.SelectWarehouseAdapter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.EpcTagBean;
import com.txsj.scan.bean.GlobalGoodsInfo;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.LabelBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.event.Action;
import com.txsj.scan.presenter.ReadLabelPresenter;
import com.txsj.scan.reader.EpcUtils;
import com.txsj.scan.reader.setpage.Setting;
import com.txsj.scan.service.UpdateService;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.TextUtil;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.view.IReadLabelView;
import com.txsj.scan.widget.TSnackbarView;
import com.txsj.scan.widget.dialog.CustomDialog;
import com.txsj.scan.widget.dialog.ScanningDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangchuangjun on 2018/11/26
 * Desc: 首页
 */

public class ReadLabelActivity extends BaseActivity<ReadLabelPresenter> implements View.OnClickListener, IReadLabelView {

    private TextView tv_unbind_count, tv_start, login_out, tv_user_name, tv_brandName, tv_update, tv_previous_step,
            tv_setting, tv_all_count, tv_warehouse, tv_other_warehouse, tv_already_settled, tv_refresh;
    private TextView tv_outofStock_count, tv_warehous_count;//待出库数量  待入库数量
    private ImageView iv_wshop_logo, iv_clear;
    private List<WarehouseBean> wareList;


    private Button btn_empty_reload;
    private LinearLayout view_empty;

    private RecyclerView recyclerView;
    private TextView tv_menu;
    private DrawerLayout mDrawerLayout;
    private SelectWarehouseAdapter adapter;
    private NestedScrollView nested_scroll_view;
    private VirtualKeyListenerBroadcastReceiver mVirtualKeyListenerBroadcastReceiver;

    private List<GoodsInfo> goodsInfoList;//商品列表先选商品带回的所选的商品集合
    private List<GoodsInfo> settledGoodsList;//已结算的商品集合
    private List<String> unBindGoodsList;//未绑定的标签集合
    private List<LabelBean> unBindLabelList;//未绑定的标签信息集合
    private List<EpcTagBean> allErrorEpcList; //加载到服务器所有的未出库入库的列表数据
    private List<EpcInfo> unOutOfStockEpcList; //待出库标签列表数据
    private List<EpcInfo> unWarehouseEpcList; //待入库标签列表数据

    private RelativeLayout titleBar, lay_already_settled, lay_out;
    private RelativeLayout lay_outofStock_count, lay_warehous_count; //待出库  待入库
    private ScanningDialog scanningDialog;

    private boolean isIniting = false;//初始化的时候开线程进行数据操作

    private String fromActivity;


    MyHandler handlerAdapter = new MyHandler();


    class MyHandler extends Handler {
        public MyHandler() {
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x223:
                    hideLoading();
                    break;
                case 0x226:
                    int alreadyCount = msg.arg1;
                    tv_already_settled.setText("" + alreadyCount);
                    tv_outofStock_count.setText(unOutOfStockEpcList.size() + "");
                    tv_warehous_count.setText(unWarehouseEpcList.size() + "");
                    hideLoading();
                    adapter.upDateList();
                    adapter.notifyDataSetChanged();
                    break;
                case 0x227:
                    hideLoading();
                    int count = msg.arg1;
                    tv_unbind_count.setText("" + count);
                    break;
                case 0x228:
                    hideLoading();
                    tv_unbind_count.setText("" + unBindLabelList.size());
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_label);
        this.wareList = new ArrayList<>();
        initView();
        initData();
        EpcUtils.getInstance(this).connectPort();
        EventBus.getDefault().register(this);
        //获取商品和标签库
//        if (!PreferenceUtil.getInstance().getBoolean(PreferenceUtil.GOODS_IS_LOADED, false)
//                || !PreferenceUtil.getInstance().getBoolean(PreferenceUtil.LABEL_IS_LOADED, false)) {
//            loadLabelAndGoods();
//        }
        if (!PreferenceUtil.getInstance().getBoolean(PreferenceUtil.LABEL_IS_LOADED, false)) {
            loadLabelAndGoods();
        }
        //获取仓库列表
        presenter.getWarehouseHttp();
        presenter.getAllEpcTagIds();
        initViewService();
    }

    private void initData() {
        if (null == getIntent() && TextUtils.isEmpty(getIntent().getStringExtra("data")) && TextUtils.isEmpty(getIntent().getStringExtra("type")))
            return;
        goodsInfoList = new ArrayList<>();
        settledGoodsList = new ArrayList<>();
        unBindGoodsList = new ArrayList<>();
        unBindLabelList = new ArrayList<>();
        allErrorEpcList = new ArrayList<>();
        unOutOfStockEpcList = new ArrayList<>();
        unWarehouseEpcList = new ArrayList<>();
        final String json = getIntent().getStringExtra("data");
        final String type = getIntent().getStringExtra("type");//0:说明部分商品筛选
        fromActivity = getIntent().getStringExtra("from");
        /**
         * 在数据进行初始化的时候，如果商品数据量较大，则会出现卡顿的情况，需开子线程处理
         */
        isIniting = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if ("0".equals(type)) {
                    goodsInfoList = GsonFactory.getObjectList(json, GoodsInfo.class);
                    //将选择好的商品信息传入到presenter中
                    if (null != presenter) presenter.setGoodsInfoList(goodsInfoList);
                    isIniting = false;
                } else if ("1".equals(type)) {//说明是全部的商品
                    List<GlobalGoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getGlobalGoodsInfoDao().loadAll();
                    goodsInfoList = GsonFactory.getObjectList(new Gson().toJson(list), GoodsInfo.class);
                    if (null != presenter) presenter.setGoodsInfoList(goodsInfoList);
                    isIniting = false;
                }
            }
        }).start();
    }

    /**
     * 重新刷新标签和商品数据
     */
    private void loadLabelAndGoods() {
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, true);
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, false);//本地记录加载失败
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.GOODS_IS_LOADED, false);//本地记录加载失败
        GreenDaoUtils.getSingleTon().deleteAll();
        presenter.getGoodsAndTagHttp();
    }

    /**
     * 开启一个服务定期更新数据
     */
    private void initViewService() {
        Intent intent = new Intent(ReadLabelActivity.this, UpdateService.class);
        startService(intent);
    }

    @Override
    protected ReadLabelPresenter providePresenter() {
        return presenter = new ReadLabelPresenter(this);
    }

    private void initView() {
        titleBar = findViewById(R.id.mTitle);
        lay_already_settled = (RelativeLayout) findViewById(R.id.lay_already_settled);
        lay_warehous_count = (RelativeLayout) findViewById(R.id.lay_warehous_count);
        lay_outofStock_count = (RelativeLayout) findViewById(R.id.lay_outofStock_count);
        lay_out = (RelativeLayout) findViewById(R.id.lay_out);
        nested_scroll_view = (NestedScrollView) findViewById(R.id.nested_scroll_view);
        tv_unbind_count = (TextView) findViewById(R.id.tv_unbind_count);
        tv_already_settled = (TextView) findViewById(R.id.tv_already_settled);
        tv_outofStock_count = (TextView) findViewById(R.id.tv_outofStock_count);
        tv_warehous_count = (TextView) findViewById(R.id.tv_warehous_count);
        tv_previous_step = (TextView) findViewById(R.id.tv_previous_step);
        tv_all_count = (TextView) findViewById(R.id.tv_all_count);
        btn_empty_reload = (Button) findViewById(R.id.btn_empty_reload);
        view_empty = (LinearLayout) findViewById(R.id.view_empty);
        tv_refresh = (TextView) findViewById(R.id.tv_refresh);
        tv_update = (TextView) findViewById(R.id.tv_update);
        tv_warehouse = (TextView) findViewById(R.id.tv_warehouse);
        tv_other_warehouse = (TextView) findViewById(R.id.tv_other_warehouse);
        tv_menu = (TextView) findViewById(R.id.tv_menu);
        tv_start = (TextView) findViewById(R.id.tv_start);
        iv_clear = (ImageView) findViewById(R.id.iv_clear);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        adapter = new SelectWarehouseAdapter(this);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setListener(new SelectWarehouseAdapter.OnItemClickListener() {
            @Override
            public void onCLick(final int position) {
                if (adapter.getShowWarehouseList().get(position).getCount() == 0) {
                    showErrorMsg("该商品仓库下无数据");
                    return;
                }
                if (tv_start.getText().toString().equals(("结束"))) {
                    final CustomDialog dialog = new CustomDialog(ReadLabelActivity.this);
                    dialog.setContent("结束读取标签才能继续，是否继续？");
                    dialog.setOkVisiable(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startStop();
                            if (fromActivity.equals("AllocationApplyDetailsActivity")) {

                                Intent intent = new Intent(ReadLabelActivity.this, AllocationEpcActivity.class);
                                intent.putExtra("source", new Gson().toJson(adapter.getWarehouse(position)));
                                intent.putExtra("detailsBean", getIntent().getStringExtra("detailsBean"));
                                intent.putExtra("warehouse_list", new Gson().toJson(adapter.getShowWarehouseList()));
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(ReadLabelActivity.this, WarehouseDetailActivity.class);
                                intent.putExtra("source", new Gson().toJson(adapter.getWarehouse(position)));
                                intent.putExtra("warehouse_list", new Gson().toJson(adapter.getShowWarehouseList()));
                                startActivity(intent);
                            }
                            dialog.dismiss();
                        }
                    });
                    dialog.setCancelVisiable();
                    dialog.show();
                } else {
                    if (!TextUtils.isEmpty(fromActivity) && fromActivity.equals("AllocationApplyDetailsActivity")) {
                        Intent intent = new Intent(ReadLabelActivity.this, AllocationEpcActivity.class);
                        intent.putExtra("source", new Gson().toJson(adapter.getWarehouse(position)));
                        intent.putExtra("detailsBean", getIntent().getStringExtra("detailsBean"));
                        intent.putExtra("warehouse_list", new Gson().toJson(adapter.getShowWarehouseList()));
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(ReadLabelActivity.this, WarehouseDetailActivity.class);
                        intent.putExtra("source", new Gson().toJson(adapter.getWarehouse(position)));
                        intent.putExtra("warehouse_list", new Gson().toJson(adapter.getShowWarehouseList()));
                        startActivity(intent);
                    }
                }
            }
        });

        scanningDialog = new ScanningDialog(this);
        scanningDialog.setListener(new ScanningDialog.OnScanEndListener() {
            @Override
            public void onEnd() {
                startStop();//开始或结束盘存
            }

            @Override
            public void onKeyDownF4() {
                startStop();//开始或结束盘存
            }
        });

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

        login_out = (TextView) navigationView.findViewById(R.id.login_out);
        tv_setting = (TextView) navigationView.findViewById(R.id.tv_setting);
        iv_wshop_logo = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.iv_wshop_logo);
        tv_user_name = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_user_name);
        tv_brandName = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_brandName);

        tv_user_name.setText("***");
        tv_brandName.setText(TextUtil.jiaMiPhone(PreferenceUtil.getInstance().getString(PreferenceUtil.MOBILE, "")));
        tv_start.setText("开始");
        tv_start.setOnClickListener(this);
        tv_menu.setOnClickListener(this);
        login_out.setOnClickListener(this);
        tv_setting.setOnClickListener(this);
        tv_other_warehouse.setOnClickListener(this);
        tv_warehouse.setOnClickListener(this);
        tv_refresh.setOnClickListener(this);
        btn_empty_reload.setOnClickListener(this);
        tv_previous_step.setOnClickListener(this);
        lay_already_settled.setOnClickListener(this);
        lay_warehous_count.setOnClickListener(this);
        lay_outofStock_count.setOnClickListener(this);

        lay_out.setOnClickListener(this);
        iv_clear.setOnClickListener(this);

        view_empty.setVisibility(View.GONE);
    }

    /**
     * 开始扫描
     */
    private void startStop() {
        if (EpcUtils.getInstance(ReadLabelActivity.this).isStarted()) {
            tv_start.setText("开始");
            startScan(false);
        } else {
            tv_start.setText("结束");
            startScan(true);
        }
        EpcUtils.getInstance(this).startStop();
    }

    /**
     * 开始对比
     */
    public void startScan(boolean isStart) {
        presenter.scan(isStart);
        //扫描弹框是否显示
        setScanDialogState(isStart);
    }

    /**
     * 设置扫描框是否显示
     *
     * @param isStart
     */
    private void setScanDialogState(boolean isStart) {
        if (isStart) {
            if (null == scanningDialog) {
                scanningDialog = new ScanningDialog(this);
            }
            if (scanningDialog.isShowing()) return;
            scanningDialog.show();
        } else {
            scanningDialog.dismiss();
        }
    }


    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMain(Action event) {
        switch (event.getType()) {
            case Constants.up_remove_data:
                LabelBean labelBean = (LabelBean) event.getContent();
                updateUnbindList(labelBean);
                break;
//            case Constants.up_reAdd_data:
//                LabelBean labelBean1 = (LabelBean) event.getContent();
//                reAddUnbindList(labelBean1);
//                break;
        }
    }

    /**
     * 绑定完标签后在未绑定标签页去掉该标签
     *
     * @param labelBean
     */
    private void updateUnbindList(final LabelBean labelBean) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean isContain = false;
                int position = 0;
                for (int i = 0; i < unBindLabelList.size(); i++) {
                    if (labelBean.getStrEpc().equals(unBindLabelList.get(i).getStrEpc())) {
                        isContain = true;
                        position = i;
                        break;
                    }
                }
                if (isContain) {
                    unBindLabelList.remove(position);
                    handlerAdapter.sendEmptyMessage(0x228);
                }
            }
        }).start();
    }

//    /**
//     * 取消绑定标签后重新添加到未绑定标签页
//     * @param labelBean
//     */
//    private void reAddUnbindList(final LabelBean labelBean) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                boolean isContain = false;
//                for (int i = 0;i<unBindLabelList.size();i++){
//                    if (labelBean.getStrEpc().equals(unBindLabelList.get(i).getStrEpc())){
//                        isContain = true;
//                        break;
//                    }
//                }
//                if (!isContain){
//                    unBindLabelList.add(labelBean);
//                    handlerAdapter.sendEmptyMessage(0x228);
//                }
//            }
//        }).start();
//    }

    @Override
    protected void onStart() {
        super.onStart();
        mVirtualKeyListenerBroadcastReceiver = new VirtualKeyListenerBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        this.registerReceiver(mVirtualKeyListenerBroadcastReceiver, intentFilter);
        if (mSwitchFlag) {
            ModuleManager.newInstance().setUHFStatus(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EpcUtils.getInstance(this).onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (null == intent || null == intent.getStringExtra("from")) return;
        fromActivity = intent.getStringExtra("from");
        if ("AllocationActivity".equals(fromActivity) || "AllocationApplyDetailsActivity".equals(fromActivity)) {
            nested_scroll_view.smoothScrollTo(0, 0);
            tv_unbind_count.setText("0");
            tv_already_settled.setText("0");
            tv_all_count.setText("0");
            adapter.clear();
            presenter.clear();
//            loadLabelAndGoods();//暂时不打开，进行本地更新

            GreenDaoUtils.getSingleTon().getmDaoSession().getUnusefulEpcDao().deleteAll();
            GreenDaoUtils.getSingleTon().getmDaoSession().getTagInfoDao().deleteAll();
            GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().deleteAll();
            GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().deleteAll();
            presenter.getAllEpcTagIds();

//            String json = intent.getStringExtra("data");
//            String warehouseJson = intent.getStringExtra("warehouse");
//            List<GoodsInfo> goodsList = GsonFactory.getObjectList(json, GoodsInfo.class);
//            WarehouseBean warehouseBean = new Gson().fromJson(warehouseJson, WarehouseBean.class);
//            updateLabelSql(goodsList, warehouseBean);
        } else if ("InventoryActivity".equals(fromActivity)) {
            showErrorMsg("盘点成功");
            nested_scroll_view.smoothScrollTo(0, 0);
            tv_unbind_count.setText("0");
            tv_already_settled.setText("0");
            tv_all_count.setText("0");
            adapter.clear();
            presenter.clear();

            GreenDaoUtils.getSingleTon().getmDaoSession().getUnusefulEpcDao().deleteAll();
            GreenDaoUtils.getSingleTon().getmDaoSession().getTagInfoDao().deleteAll();
            GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().deleteAll();
            GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().deleteAll();

        }
    }

    /**
     * 通过提交完成的数据进行点对点标签更新
     *
     * @param goodsList     标签对应的商品列表
     * @param warehouseBean 要更新到的仓库
     */
    private void updateLabelSql(final List<GoodsInfo> goodsList, final WarehouseBean warehouseBean) {
        showErrorMsg("调拨成功");
        showLoading();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (GoodsInfo goodsInfo : goodsList) {
                    for (EpcInfo epcInfo : goodsInfo.getEpcList()) {
                        //解析
                        String epcCode = epcInfo.getStrEpc().substring(9, epcInfo.getStrEpc().length());
                        long id = Long.parseLong(epcCode, 16);
                        //对比筛选
                        List<EpcInfo> epcList = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().queryBuilder()
                                .where(EpcInfoDao.Properties.Tag_id.eq(id))
                                .list();
                        if (epcList != null && epcList.size() > 0) {
                            EpcInfo updateEpc = epcList.get(0);
                            updateEpc.setCurrent_sell_warehouse_id(warehouseBean.getWarehouse_id());
                            GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().insertOrReplace(updateEpc);
                        }
                    }
                }
                handlerAdapter.sendEmptyMessage(0x223);
            }
        }).start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_start:
                startStop();
                break;
            case R.id.tv_menu:
//                mDrawerLayout.openDrawer(Gravity.LEFT);
                onBackPressed();
                break;
            case R.id.login_out:
                loginOut();
                break;
            case R.id.tv_setting:
                toSetting();
                break;
            case R.id.tv_other_warehouse:
                //点击刷新
                break;
            case R.id.tv_warehouse:
                //todo 点击刷新
                break;
            case R.id.btn_empty_reload:
                presenter.getWarehouseHttp();
                break;
            case R.id.tv_previous_step://上一步
                onBackPressed();
                break;
            case R.id.lay_already_settled://已结算
                toSettledGoodsActivity();
                break;
            case R.id.lay_outofStock_count:
                toUnWhoreEpcActivity(unOutOfStockEpcList, "待出库标签");
                break;
            case R.id.lay_warehous_count:
                toUnWhoreEpcActivity(unWarehouseEpcList, "待入库标签");
                break;
            case R.id.lay_out://未绑定
                toUnbindLabelActivity();
                break;
            case R.id.iv_clear://清空扫描的标签
                toClear();
                break;
            case R.id.tv_refresh:
            case R.id.tv_update:
                nested_scroll_view.smoothScrollTo(0, 0);
                tv_unbind_count.setText("0");
                tv_already_settled.setText("0");
                tv_all_count.setText("0");
                adapter.clear();
                presenter.clear();
                loadLabelAndGoods();
                break;
        }
    }

    /**
     * 清空扫描到的标签
     */
    private void toClear() {
        final CustomDialog dialog = new CustomDialog(this);
        dialog.setContent("确认重新扫描？");
        dialog.setCancelVisiable();
        dialog.setOkVisiable(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nested_scroll_view.smoothScrollTo(0, 0);
                tv_unbind_count.setText("0");
                tv_already_settled.setText("0");
                tv_all_count.setText("0");
                tv_outofStock_count.setText("0");
                tv_warehous_count.setText("0");
                if (null != unOutOfStockEpcList) unOutOfStockEpcList.clear();
                if (null != allErrorEpcList) allErrorEpcList.clear();
                adapter.clear();
                presenter.clear();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 去已结算界面
     */
    private void toSettledGoodsActivity() {
        if (settledGoodsList.size() == 0) return;
        if (tv_start.getText().toString().equals(("结束"))) {
            final CustomDialog dialog = new CustomDialog(ReadLabelActivity.this);
            dialog.setContent("结束读取标签才能继续，是否继续？");
            dialog.setOkVisiable(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startStop();
                    Intent intent = new Intent(ReadLabelActivity.this, SettledGoodsActivity.class);
                    intent.putExtra("data", new Gson().toJson(settledGoodsList));
                    startActivity(intent);
                    dialog.dismiss();
                }
            });
            dialog.setCancelVisiable();
            dialog.show();
        } else {
            Intent intent = new Intent(ReadLabelActivity.this, SettledGoodsActivity.class);
            intent.putExtra("data", new Gson().toJson(settledGoodsList));
            startActivity(intent);
        }
    }


    /**
     * 去待出库  待入库标签详情页面
     *
     * @param epcInfoList
     */
    private void toUnWhoreEpcActivity(final List<EpcInfo> epcInfoList, final String title) {
        if (epcInfoList.size() == 0) {
            return;
        }
        if (tv_start.getText().toString().equals(("结束"))) {
            final CustomDialog dialog = new CustomDialog(ReadLabelActivity.this);
            dialog.setContent("结束读取标签才能继续，是否继续？");
            dialog.setOkVisiable(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startStop();
                    Intent intent = new Intent(ReadLabelActivity.this, UnTakeEpcLableActivity.class);
                    intent.putExtra("data", new Gson().toJson(epcInfoList));
                    intent.putExtra("title", title);
                    startActivity(intent);
                    dialog.dismiss();
                }
            });
            dialog.setCancelVisiable();
            dialog.show();
        } else {
            Intent intent = new Intent(ReadLabelActivity.this, UnTakeEpcLableActivity.class);
            intent.putExtra("data", new Gson().toJson(epcInfoList));
            intent.putExtra("title", title);
            startActivity(intent);
        }
    }

    /**
     * 去未绑定标签页
     */
    private void toUnbindLabelActivity() {
        if (unBindGoodsList.size() == 0) return;
        if (tv_start.getText().toString().equals(("结束"))) {
            final CustomDialog dialog = new CustomDialog(ReadLabelActivity.this);
            dialog.setContent("结束读取标签才能继续，是否继续？");
            dialog.setOkVisiable(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startStop();
                    Intent intent1 = new Intent(ReadLabelActivity.this, UnbindLabelActivity.class);
                    intent1.putStringArrayListExtra("data", (ArrayList<String>) unBindGoodsList);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("label", (Serializable) unBindLabelList);
                    intent1.putExtra("bundle", bundle);
                    startActivity(intent1);
                    dialog.dismiss();
                }
            });
            dialog.setCancelVisiable();
            dialog.show();
        } else {
            Intent intent1 = new Intent(ReadLabelActivity.this, UnbindLabelActivity.class);
            intent1.putStringArrayListExtra("data", (ArrayList<String>) unBindGoodsList);
            Bundle bundle = new Bundle();
            bundle.putSerializable("label", (Serializable) unBindLabelList);
            intent1.putExtra("bundle", bundle);
            startActivity(intent1);
        }
    }

    /**
     * 扫码枪设置
     */
    private void toSetting() {
        Intent intent = new Intent(ReadLabelActivity.this, Setting.class);
        startActivity(intent);
    }

    /**
     * 退出登录
     */
    private void loginOut() {
        AlertDialog dialog = new AlertDialog.Builder(context())
                .setTitle("确定退出登录？")
                .setCancelable(true)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        PreferenceUtil.getInstance().removeAll();
                        GreenDaoUtils.getSingleTon().getmDaoSession().clear();
                        ModuleManager.newInstance().setUHFStatus(false);
                        Intent intent = new Intent(ReadLabelActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .create();
        dialog.show();

    }

    @Override
    public Context context() {
        return this;
    }


    @Override
    public void onError(String msg) {
        hideLoading();
        showErrorMsg(msg);
    }

    @Override
    public void onSuccess() {
//        if (PreferenceUtil.getInstance().getBoolean(PreferenceUtil.GOODS_IS_LOADED, false)
//                && PreferenceUtil.getInstance().getBoolean(PreferenceUtil.LABEL_IS_LOADED, false)) {
//            PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, false);
//            hideLoading();
//        }
        if (PreferenceUtil.getInstance().getBoolean(PreferenceUtil.LABEL_IS_LOADED, false)) {
            PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, false);
            hideLoading();
        }
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onUpdateCount(List<LabelBean> unUsefulLabelList, List<String> unUsefulList, List<EpcInfo>
            usefulList, long usefulCount, long allCount) {
        hideLoading();
        tv_unbind_count.setText("" + unUsefulList.size());
        this.unBindGoodsList = unUsefulList;
        this.unBindLabelList = unUsefulLabelList;
        tv_all_count.setText(allCount + "");
        scanningDialog.updateScanCount(allCount);//更新弹出扫描框显示的个数
        if (usefulList.size() != 0) {
            filterUsefulList(usefulList);
        }
//        getAlreadySettledCount();//设置已结算数量
//        tv_unknown_count.setText(unKnown + "");
    }

    private void filterUsefulList(final List<EpcInfo> usefulList) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (wareList.size() == 0) return;
                //对warehouse中的list初始化
                for (WarehouseBean warehouse : adapter.getWarehouseList()) {
                    warehouse.setEpcList(new ArrayList<EpcInfo>());
                    warehouse.setCount(0);
                    warehouse.clearList();
                }
                //对重复的标签去重
                List<EpcInfo> tempList = new ArrayList<>();
                for (EpcInfo info : usefulList) {
                    boolean isContain = false;
                    for (EpcInfo tempEpc : tempList) {
                        if (info.getStrEpc().equals(tempEpc.getStrEpc())) {
                            isContain = true;
                        }
                    }
                    if (!isContain) {
                        tempList.add(info);
                    }
                }

                //如果没有请求成功，再次请求
                if (!isLoadSuccess) {
                    presenter.getAllEpcTagIds();
                }

                //在标签筛选进入仓库之前  先对标签进行筛选出库入库状态
                List<EpcInfo> tempList1 = new ArrayList<>();
                if (allErrorEpcList.size() > 0) {
                    for (EpcInfo info : tempList) {
                        boolean isHave = false;
                        for (EpcTagBean mEpcTag : allErrorEpcList) {
                            if (mEpcTag.getItem1() == info.getTag_id()) {
                                isHave = true;
                                if (mEpcTag.getItem2() == 4) {
                                    //待入库
                                    if (!unWarehouseEpcList.contains(info)) {
                                        unWarehouseEpcList.add(info);
                                    }

                                } else {
                                    //待出库
                                    if (!unOutOfStockEpcList.contains(info)) {
                                        unOutOfStockEpcList.add(info);
                                    }

                                }
                            }
                        }
                        if (!isHave)
                            tempList1.add(info);
                    }
                } else {
                    tempList1.addAll(tempList);
                }


                //筛选进入对应的仓库
                for (EpcInfo info : tempList1) {
                    for (WarehouseBean warehouse : adapter.getWarehouseList()) {
                        if (info.getCurrent_sell_warehouse_id() == warehouse.getWarehouse_id()) {
                            long count = warehouse.getCount();
                            if (info.getOrder_id() <= 0) {//若epcinfo已结算，则不计算到仓库中可用的数量当中
                                warehouse.setCount(++count);
                            }
                            warehouse.addEpcInfo(info);//尽管不算在仓库的数量当中，但在计算已结算数量的过程中需要从中筛选
                            break;
                        }
                    }
                }


                //接下来筛选已结算的数量
                int alreadyCount = 0;
                List<WarehouseBean> list = adapter.getWarehouseList();
                if (list.size() == 0) {
                    alreadyCount = 0;
                } else {
                    for (WarehouseBean warehouseBean : list) {
                        List<EpcInfo> epcInfoList = warehouseBean.getEpcList();
                        if (epcInfoList == null || epcInfoList.size() == 0) continue;
                        for (EpcInfo epcInfo : epcInfoList) {
                            for (GoodsInfo goodsInfo : goodsInfoList) {
                                if (goodsInfo.getGoods_id() == epcInfo.getGoods_id()) {
                                    if (epcInfo.getOrder_id() > 0) {
                                        alreadyCount++;
                                        //筛选已结算完成后进行数据的整合

                                        filterSettledGoods(goodsInfo, epcInfo);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                Message msg = new Message();
                msg.arg1 = alreadyCount;
                msg.what = 0x226;
                handlerAdapter.sendMessage(msg);
            }
        }).start();
    }


    /**
     * 在设置已结算数量的过程中，设置已结算的列表
     *
     * @param goodsInfo 用户选择商品范围内的商品
     * @param epcInfo   仓库列表里的标签
     */
    private void filterSettledGoods(GoodsInfo goodsInfo, EpcInfo epcInfo) {
        if (null == goodsInfo.getEpcList()) {
            goodsInfo.setEpcList(new ArrayList<EpcInfo>());
        }
        boolean isExit = false;
        for (EpcInfo epc : goodsInfo.getEpcList()) {
            if (epc.getStrEpc().equals(epcInfo.getStrEpc())) {
                isExit = true;
                break;
            }
        }
        if (!isExit) {
            goodsInfo.getEpcList().add(epcInfo);
        }

        if (settledGoodsList.contains(goodsInfo)) {
//            int pos = settledGoodsList.indexOf(goodsInfo);
//            boolean isContain = false;
//            for (EpcInfo srtEpc : settledGoodsList.get(pos).getEpcList()) {
//                if (epcInfo.getStrEpc().equals(srtEpc)) {
//                    isContain = true;
//                    break;
//                }
//            }
//            if (!isContain) {
//                settledGoodsList.get(pos).getEpcList().add(epcInfo);
//            }
        } else {
            settledGoodsList.add(goodsInfo);
        }

    }

    @Override
    public void onWarehouseError(String msg) {
        hideLoading();
        showErrorMsg(msg);
        view_empty.setVisibility(View.VISIBLE);
    }

    @Override
    public void onWarehouseEmpty(String msg) {
        hideLoading();
        showErrorMsg(msg);
        view_empty.setVisibility(View.VISIBLE);
    }

    @Override
    public void onWarehouseSuccess(List<WarehouseBean> list) {
        onSuccess();
        wareList.clear();
        wareList.addAll(list);
        adapter.setData(list);
        view_empty.setVisibility(View.GONE);
    }

    @Override
    public void onScanError(String msg) {
        hideLoading();
        showErrorMsg(msg);
        tv_unbind_count.setText("0");
        tv_already_settled.setText("0");
        tv_all_count.setText("0");
    }

    boolean isLoadSuccess = false;

    @Override
    public void checkShowList(List<EpcTagBean> tagBeanList) {
        isLoadSuccess = true;
        if (null == tagBeanList || tagBeanList.size() == 0) {
            return;
        }
        allErrorEpcList.clear();
        allErrorEpcList.addAll(tagBeanList);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isIniting) {
            showErrorMsg("初始化中请稍后");
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (scanningDialog.isShowing() && wd.isShowing() && PreferenceUtil.getInstance().getBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, false)) {
                return true;
            }
//            return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        } else if (event.getKeyCode() == KeyEvent.KEYCODE_F4) {//扫码枪的按钮action：KEYCODE_F4
            //开始盘存
            startStop();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private class VirtualKeyListenerBroadcastReceiver extends BroadcastReceiver {
        private final String SYSTEM_REASON = "reason";
        private final String SYSTEM_HOME_KEY = "homekey";
        private final String SYSTEM_RECENT_APPS = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String systemReason = intent.getStringExtra(SYSTEM_REASON);
                if (systemReason != null) {
                    if (systemReason.equals(SYSTEM_HOME_KEY)) {
                        System.out.println("Press HOME key");
                    } else if (systemReason.equals(SYSTEM_RECENT_APPS)) {
                        System.out.println("Press RECENT_APPS key");
                        ModuleManager.newInstance().setUHFStatus(false);
                        mSwitchFlag = true;
                    }
                }
            }
        }

    }

    public void showErrorMsg(String msg) {
        new TSnackbarView(titleBar, msg);
    }

    @Override
    protected void onDestroy() {
        //如果当前扫码枪处于扫描状态，再次调用startStop方法进行停止扫描
        if (EpcUtils.getInstance(this).isStarted()) {
            EpcUtils.getInstance(this).startStop();
        }
        //清除缓冲区里的数据
        EpcUtils.getInstance(this).clearTagList();
        EventBus.getDefault().unregister(this);
        Intent intent = new Intent(ReadLabelActivity.this, UpdateService.class);
        stopService(intent);
        this.unregisterReceiver(mVirtualKeyListenerBroadcastReceiver);
        super.onDestroy();
    }


}
